package com.easpeed.comon.temp

import android.content.Context
import android.util.Log;
import com.bigyu.utils.Logger
import androidx.core.util.Consumer
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.common.CommonConsts
import com.easpeed.comon.bean.BaseData
import com.easpeed.comon.consts.ConstsOpticalData
import com.easpeed.comon.utils.CacheHelper
import com.easpeed.comon.utils.ImageUtils
import com.easpeed.comon.utils.Line
import com.easpeed.comon.utils.NetHelper
import com.easpeed.comon.utils.Optical
import com.easpeed.comon.utils.Record
import com.easpeed.comon.utils.UploadFile
import com.easpeed.elevator.bean.LineBean
import com.easpeed.elevator.bean.OpticalBean
import com.easpeed.elevator.bean.RouteBean
import com.easpeed.user.utils.FileHelper
import java.io.File

/**
 * Created by bigyu on 2025-04-08 11:12
 * com.easpeed.comon.temp
 */
class UploadCacheData(val mContext: Context) {

    private val TAG = "UploadCacheData"

    private var progressCallback: ((success: Boolean) -> Unit)? = null
    fun setLineProgressCallback(progressCallback: (success: Boolean) -> Unit) {
        this.progressCallback = progressCallback
    }

    private var progressCallbackRoute: ((success: Boolean) -> Unit)? = null
    fun setRouteProgressCallback(progressCallback: (success: Boolean) -> Unit) {
        this.progressCallbackRoute = progressCallback
    }

    fun getLineList(): ArrayList<LineBean> {
        val lineList = FileHelper.readLineData(mContext)
        Logger.e(TAG, "线路数据为: ${lineList.size}")
        return lineList
    }

    fun getRouteList(): ArrayList<RouteBean> {
        val routeList = FileHelper.readRouteData(mContext)
        Logger.e(TAG, "路由数据为: ${routeList.size}")
        return routeList
    }


    private var mapUUid = HashMap<String, String>()

    private lateinit var netHelper: NetHelper


    fun uploadLine(list: ArrayList<LineBean>) {
        val bean = list.removeFirstOrNull() ?: return
        //上传线路数据
        netForCreate(bean.lineName) {
            if (it != null) {
                mapUUid[bean.lineId] = it.id.toString()
                progressCallback?.invoke(true)

                uploadOptical(ArrayList(bean.opticalList), it.id.toString()) {
                    uploadLine(list)
                }
            } else {
                progressCallback?.invoke(false)
                uploadLine(list)
            }
        }
    }

    fun uploadRoute(list: ArrayList<RouteBean>) {
        val bean = list.removeFirstOrNull() ?: return


        val imagePathList = bean.imagePath
        val serverUrl = ArrayList<String>()
        uploadImage(imagePathList, serverUrl) {
            bean.imagePath.clear()
            bean.imagePath.addAll(serverUrl)
            //上传路由数据
            netForUpdateRecord(bean) {
                if (it) {
                    progressCallbackRoute?.invoke(true)
                } else {
                    progressCallbackRoute?.invoke(false)
                }
                uploadRoute(list)
            }
        }
    }

    fun uploadImage(imagePathList: ArrayList<String>, serverUrl: ArrayList<String>, result: Consumer<Boolean>) {
        val url = imagePathList.removeFirstOrNull()
        if (url == null || url == "") {
            result.accept(true)
            return
        }

        netForUploadImage(url) {
            Logger.e(TAG, "uploadImage: $it")
            if (it != null) {
                serverUrl.add(it)
            } else {

            }
            uploadImage(imagePathList, serverUrl, result)
        }

    }

    fun uploadOptical(list: ArrayList<OpticalBean>, lineId: String, result: Consumer<Boolean>) {
        val opticalBean = list.removeFirstOrNull()
        if (opticalBean == null) {
            result.accept(true)
            return
        }
        val map = HashMap<String, Any?>()
        map["remark"] = opticalBean.remark
        map["opticalName"] = opticalBean.name
        map["fibreLength"] = opticalBean.length
        map["fibreCodes"] = opticalBean.codeMark
        map["fibreNum"] = opticalBean.number.toInt()
        map["hop"] = opticalBean.zjd
        map["opticalLevel"] = ConstsOpticalData.getLevelIndex(opticalBean.level)
        map["lineId"] = lineId
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        netForCreateOptical(map) {
            uploadOptical(list, lineId, result)
            if (it != null) {
                mapUUid[opticalBean.id] = it.id.toString()

                progressCallback?.invoke(true)
            } else {
                progressCallback?.invoke(false)
            }
        }
    }

    //上传线路数据
    fun netForCreate(lineName: String?, result: Consumer<Line?>) {
        val map = HashMap<String, Any>()
        map["lineName"] = "$lineName"
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext)
        }
        netHelper.netForCreateLine(false, map, Consumer<BaseData<Line>> {
            if (it.code == 200 && it.data != null) {
                result.accept(it.data)
            } else {
                result.accept(null)
            }
        })
    }

    //上传光缆数据
    fun netForCreateOptical(map: HashMap<String, Any?>, result: Consumer<Optical>) {
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext)
        }
        netHelper.netForCreateOptical(false, map, Consumer<BaseData<Optical>> {
            if (it.code == 200) {
                result.accept(it.data)
            } else {
                result.accept(it.data)
            }
        }
        )
    }


    private fun netForUploadImage(filePath: String, result: Consumer<String?>) {
        val file = File(filePath)
        if (!file.exists()) {
            result.accept(null)
            return
        }
        val newFile = ImageUtils.compressImage(file)
        if (newFile == null) {
            result.accept(null)
            return
        }
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForUploadFile(false, newFile, Consumer<BaseData<UploadFile>> {
            if (it.code == 200) {
                var fileUrl = it.data?.fileUrl
                result.accept(fileUrl)
            } else {
                result.accept(null)
            }
        })
    }


    private fun netForUpdateRecord(bean: RouteBean, result: Consumer<Boolean>) {
        val map = HashMap<String, Any?>()
//        map["id"] = bean.routeId

        val newLineId = mapUUid[bean.lineId]

        val newOpticalId = mapUUid[bean.opticalId]
        if (newLineId == null || newOpticalId == null) {
            result.accept(false)
            return
        }

        map["lineId"] = newLineId
        map["opticalId"] = newOpticalId
        map["deviceCode"] = CommonConsts.targetDeviceId

        map["recordType"] = bean.routeTypeId
        map["fibreCodes"] = bean.codeMark
        map["distance"] = bean.distance
        map["placeDesc"] = bean.addressRemark
        map["remark"] = bean.routeRemark
        map["latitude"] = bean.lat
        map["longitude"] = bean.lng
        bean.imagePath.takeIf {
            it.isNotEmpty()
        }?.let {
            map["pictures"] = bean.imagePath.joinToString(";")
        }

        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForCreateRecord(false, map, Consumer<BaseData<Record>> {
            if (it.code == 200) {
                result.accept(true)
            } else {
                result.accept(false)
            }
        })
    }


}